﻿using Admin.Common;
using Admin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using YTCMS.Core;
using YTCMS.Services.Services;

namespace Admin.Controllers
{
    public class LoginController : Controller
    {
        private readonly IusersService _users;
        public LoginController(IusersService users)
        {
            _users = users;
        }
        //
        // GET: /Login/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(LoginViewModel login)
        {
            if (ModelState.IsValid)
            {
                var member = _users.Get(s => s.UserName == login.UserName);
                if (member == null)
                    return View();
                if (member.State != (int)CommonState.正常)
                    return View();
                if (member.type != (int)usertype.管理员)
                    return View();
                var encodepassword = Cryptographer.EncodePassword(login.Password, 1, member.EncryptContent);
                if (member.Pwd.Equals(encodepassword))
                {
                    var user = Newtonsoft.Json.JsonConvert.SerializeObject(member);
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(100, member.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, user);
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    authCookie.HttpOnly = true;
                    authCookie.Secure = FormsAuthentication.RequireSSL;
                    authCookie.Domain = FormsAuthentication.CookieDomain;
                    authCookie.Path = FormsAuthentication.FormsCookiePath;
                    authCookie.Expires = DateTime.Now.AddMinutes(30); //默认30分钟
                    Response.Cookies.Remove(authCookie.Name);
                    Response.Cookies.Add(authCookie);
                    var ReturnUrl = HttpUtility.UrlDecode(ControllerContext.RequestContext.HttpContext.Request.Form["ReturnUrl"], ControllerContext.RequestContext.HttpContext.Request.ContentEncoding);
                    if (ReturnUrl != null && Url.IsLocalUrl(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult signout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("index", "login");
        }
	}
}